<?php
namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\common\model\Field as FieldModel;
use app\common\model\UserAuthRule;

class Field extends AdminBase
{
    protected function _initialize()
    {
        parent::_initialize();
    }

    public function index()
    {
        return $this->fetch('index');
    }
    public function index_json($limit='15')
    {
        $list = FieldModel::with(['userrule'])->order('id desc')->paginate($limit);
        $this->result($list);
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $result = FieldModel::create($param);
            if ($result == true) {
                insert_admin_log('添加了自定义分类');
                $this->success('添加成功');
            } else {
                $this->error($this->errorMsg);
            }
        }
        $userAuthRule = collection(UserAuthRule::where(['status' => 1])->order('sort_order asc')->select())->toArray();
        return $this->fetch('save',['auth'=>list_to_level($userAuthRule)]);
    }

    public function edit($id)
    {
        if ($this->request->isPost()) {
            $param  = $this->request->param();
            //更新数据
            $resule = FieldModel::update($param,['id'=>$param['id']]);
            if ( $resule == true) {
                insert_admin_log('修改了自定义类型');
                $this->success('修改成功');
            } else {
                $this->error($this->errorMsg);
            }
        }
        $userAuthRule = collection(UserAuthRule::where(['status' => 1])->order('sort_order asc')->select())->toArray();
        $data = FieldModel::where('id', $id)->find();
        //$this->result($data['default_field']->type);
        return $this->fetch('save', [
            'data'  => $data,
            'auth'  => list_to_level($userAuthRule)
        ]);
    }

    public function del()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            FieldModel::destroy($param['id']);
            insert_admin_log('删除了自定义类型');
            $this->success('删除成功');
            
        }
    }

}
